import * as XLSX from 'xlsx'
import FileSaver from 'file-saver'
/**
 * base64格式转excel格式文件并下载
 * @param {*} base64result 后端返回的base64格式的数据
 * @param {*} filename 下载文件的名字
 */
function dataURLtoBlob(base64result, filename) {
  var raw = window.atob(base64result);
  var uInt8Array = new Uint8Array(base64result.length);
  for (var i = 0; i < raw.length; i++) {
    uInt8Array[i] = raw.charCodeAt(i);
  }

  const link = document.createElement("a");
  const blob = new Blob([uInt8Array], {
    type: 'application/vnd.ms-excel'
  })

  link.style.display = 'none';
  link.href = URL.createObjectURL(blob);
  link.setAttribute('download', filename + '.xls');

  document.body.appendChild(link)
  link.click()

  document.body.removeChild(link)

}
// 解析Excel数据为二进制数据流， 写入工具函数utils.js 中方便其他模块使用
const readFile = file => {
  return new Promise(resolve => {
    let reader = new FileReader()
    reader.readAsBinaryString(file)
    reader.onload = ev => {
      resolve(ev.target.result)
    }
  })
}
// 解析Excel数据为base64格式， 写入工具函数utils.js 中方便其他模块使用
const getBase64 = file => {
  return new Promise(resolve => {
    let reader = new FileReader()
    // reader.readAsDataURL(file)
    reader.readAsArrayBuffer(file)
    reader.onload = ev => {
      console.log(ev)
      //let fileData = ev.target.result.replace(/data.+?;base64,/, "");
      let Base64 = require("js-base64").Base64;
      var fileData = Base64.encode(ev.target.result);
      resolve(fileData)
    }
  })
}
function exportExcel(dom, fileName) {
  // 前面这五行代码作用就是去掉导出重复的表 就是导出的时候我这边会导出两个一样的表格，可能是因为右侧的fixed导致的，所以在导出的时候要删除掉
  let tableDom = dom.cloneNode(true)
  let elTableFixedRight = tableDom.querySelector(".el-table__fixed-right")
  let elTableFixed = tableDom.querySelector(".el-table__fixed")
  if (elTableFixedRight) tableDom.removeChild(elTableFixedRight);
  if (elTableFixed) tableDom.removeChild(elTableFixed);

  let wb = XLSX.utils.table_to_book(tableDom, { raw: true })
  let wbout = XLSX.write(wb, {
    bookType: 'xlsx',
    bookSST: true,
    type: 'array'
  })
  try {
    FileSaver.saveAs(new Blob([wbout], { type: "application/octet-stream" }), fileName);
  } catch (e) {
    console.error(e, wbout, '----->>>')
  }
}

function exportDataToExcel(data,fileName) {
  // 创建工作簿
  const workbook = XLSX.utils.book_new();

  // 创建工作表
  const worksheet = XLSX.utils.json_to_sheet(data);

  // 将工作表添加到工作簿
  XLSX.utils.book_append_sheet(workbook, worksheet, "Sheet1");

  // 将工作簿转换为二进制数据
  const excelBuffer = XLSX.write(workbook, { bookType: "xlsx", type: "array" });

  // 创建 Blob 对象
  const blob = new Blob([excelBuffer], { type: "application/octet-stream" });

  // 生成下载链接
  const url = window.URL.createObjectURL(blob);

  // 创建下载链接
  const link = document.createElement("a");
  link.href = url;
  link.setAttribute("download", fileName);

  // 模拟点击下载链接以触发下载
  link.click();

  // 释放 URL 对象
  window.URL.revokeObjectURL(url);
}


export {
  dataURLtoBlob,
  readFile,
  getBase64,
  exportExcel,
  exportDataToExcel
}